package by.grsu.verkhovodko.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.verkhovodko.entity.Passenger;
import by.grsu.verkhovodko.table.PassengerTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class PassengerDao extends AbstractDao<PassengerTable, Passenger> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -395079376414141938L;

	public PassengerDao(final String rootFolderPath) {
		super(rootFolderPath);
	}
 
	
	public Passenger searchByLogin(String login) {
		final PassengerTable passengerTable = deserializeFromXml();
		Passenger pass = new Passenger();
		for (final Passenger p : passengerTable.getRows()) {
			if (p.getLogin().equals(login)) {
				pass = p;
				break;
			}
		}
		return pass;
	}
	
	@Override
	public void saveNew(final Passenger newPassenger) {
		// set ID
		newPassenger.setId(getNextId());
		// get existing data
		final PassengerTable passengerTable = deserializeFromXml();
		// add new row
		passengerTable.getRows().add(newPassenger);
		// save data
		serializeToXml(passengerTable);
		
	}

	@Override
	public void update(final Passenger entity) {
		// get existing data
		final PassengerTable passengerTable = deserializeFromXml();
		// find by ID
		for (final Passenger row : passengerTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setId(entity.getId());
				row.setLogin(entity.getLogin());
				row.setPassword(entity.getPassword());
				//row.setApplicationIdList(entity.getApplicationIdList());
				//row.setBillIdList(entity.getBillIdList());
				break;
			}
		}
		// save updated table
		serializeToXml(passengerTable);
	}

	@Override
	public Passenger get(final Serializable id) {
		// get existing data
		final PassengerTable passengerTable = deserializeFromXml();
		// find by ID
		for (final Passenger row : passengerTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}
	
	@Override
	public List<Passenger> getAll() {
		// get existing data
		final PassengerTable passengerTable = deserializeFromXml();
		return passengerTable.getRows();
	}
	
	@Override
	public void delete(final Serializable id) {
		// get existing data
		final PassengerTable passengerTable = deserializeFromXml();
		// find by ID
		Passenger toBeDeleted = null;
		for (final Passenger row : passengerTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		passengerTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(passengerTable);
	}

	@Override
	protected Class<PassengerTable> getTableClass() {
		return PassengerTable.class;
	}



}
